<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.back()"
      />
      <!-- 搜索组件 -->
      <van-search
        v-jujiao
        ref="search"
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        v-model.trim="kw"
        @input="inputFn"
        @search="enterFn(kw)"
      />
    </div>
    <!-- 搜索建议列表 -->
    <ul class="sugg-list" v-if="kw">
      <li
        class="sugg-item"
        v-for="(str, index) in suggList"
        :key="index"
        v-html="highLightFn(str)"
        @click="enterFn(str)"
      ></li>
    </ul>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="clearHistoryFn" />
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span
          class="history-item"
          v-for="(arr, index) in history"
          :key="index"
          @click="hisClickFn(arr)"
          v-text="arr"
          @touchstart="touchstartFn(index)"
          @touchmove="touchmoveFn"
          @touchend="touchendFn"
          @contextmenu.prevent
          @selectstart.prevent
          >{{ arr }}</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import { getSearchSuggListAPI } from '@/api/search.js'
import { Dialog } from 'vant'

export default {
  data () {
    return {
      kw: '', // 搜索关键字
      timer: null, // 防抖, 用的定时器
      suggList: [], // 联想菜单列表
      history: JSON.parse(window.localStorage.getItem('history')) || [] // 搜索历史
    }
  },
  watch: {
    history (newVal) {
      window.localStorage.setItem('history', JSON.stringify(newVal))
    }
  },
  activated () {
    this.$refs.search.querySelector('input').focus()
  },
  methods: {
    // 触屏开始 （按下了）
    touchstartFn (i) {
      this.timer = setTimeout(async () => {
        try {
          await Dialog.confirm({
            message: '确认删除该条记录？'
          })
          this.history.splice(i, 1)
        } catch (err) { }
      }, 800)
    },
    // 触屏移动
    touchmoveFn () {
      clearTimeout(this.timer)
    },
    // 触屏抬起
    touchendFn () {
      clearTimeout(this.timer)
    },
    // 清空历史记录
    async clearHistoryFn () {
      try {
        await Dialog.confirm({
          message: '确定清理所有历史记录吗？'
        })
        this.history = []
        window.localStorage.removeItem('history')
      } catch (e) { }
    },
    inputFn () {
      // 关闭上一次 延迟器
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (this.kw.length === 0) return // 防止空内容触发下面逻辑
        // 调用 联想菜单 接口--获取数据
        const resq = await getSearchSuggListAPI({
          keyword: this.kw
        })
        const { options } = resq.data
        // for (let i = 0; i < options.length; i++) {
        //   options[i] = options[i].replace(/ /g, '')
        // }

        this.suggList = options.map(str => str.replace(/ /g, ''))
        // this.suggList = options
      }, 500)
    },
    // 联想菜单，关键字高亮
    highLightFn (str) {
      // 找出关键字部分
      const regexp = new RegExp(this.kw, 'ig')
      return str.replace(regexp, match => {
        return `<span style='color:red;'>${match}</span>`
      })
    },
    hisClickFn (str) {
      this.kw = ''
      // 异步跳转
      setTimeout(() => {
        this.$router.push({
          path: `/search/${str}`
        })
      })
    },
    // 输入框回车
    enterFn (str) {
      if (!this.history.includes(str)) {
        this.history.push(str)
      }
      this.kw = ''
      // 异步跳转
      setTimeout(() => {
        this.$router.push({
          path: `/search/${str}`
        })
      })
    }
  }
}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
